/*
 * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package cn.qiao.benchmark;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import io.lettuce.core.support.ConnectionPoolSupport;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 1)//预热轮数
@Measurement(iterations = 1, time = 1, timeUnit = TimeUnit.SECONDS)
@Threads(10)//线程数
@Fork(1) //fork的次数，如果想用Autowired自动注入，这个填0
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Thread)
public class MyBenchmark {

    private JedisServiceImpl jedisService;

    private LettuceServiceImpl lettuceService;

    private LettuceImpl lettuce;
    private LettucePoolImpl lettucePool;


    @Setup
    public void init(){
        jedisService = new JedisServiceImpl(getJedisPool());
        lettuceService = new LettuceServiceImpl(getRedisConnectionFactory());
        lettuce = new LettuceImpl(getLettuce());
        lettucePool = new LettucePoolImpl(getLettucePool());
    }

    private RedisClient getLettuce() {
        return RedisClient.create("redis://localhost:6379");
    }


    JedisPool getJedisPool(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10); // 设置最大连接数
        jedisPoolConfig.setMaxIdle(5);   // 设置最大空闲连接数
        // 创建 Jedis 连接池
        return new JedisPool(jedisPoolConfig, "localhost", 6379,3,null,3);
    }

    public static RedisConnectionFactory getRedisConnectionFactory(){
        // Redis服务器配置
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setHostName("localhost");
        redisConfig.setPort(6379);
        redisConfig.setDatabase(3);

        // 客户端资源配置（包括连接池配置）
        ClientResources clientResources = DefaultClientResources.builder()
                .computationThreadPoolSize(4)
                .ioThreadPoolSize(4)
                .build();
        // Lettuce连接工厂配置
        LettuceClientConfiguration clientConfiguration = LettuceClientConfiguration.builder()
                .clientResources(clientResources)
                .build();

        // 创建Lettuce连接工厂
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisConfig, clientConfiguration);
        lettuceConnectionFactory.afterPropertiesSet();
        return lettuceConnectionFactory;
    }

    public static  GenericObjectPool  getLettucePool(){
        RedisURI redisUri = RedisURI.builder()
                .withHost("127.0.0.1")
                .withPort(6379)
                .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                .build();
        RedisClient client = RedisClient.create(redisUri);
        //连接池配置
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(100);
        GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport.createGenericObjectPool(client::connect, poolConfig);
        return pool;
    }
//
//
//
//    @Benchmark
//    public void jedis_set(){
//        String key = "jedis-test";
//        jedisService.set(key,"test");
//    }
//
//
//    @Benchmark
//    public void jedis_get(){
//        String key = "jedis-test";
//        jedisService.get(key);
//    }
//
//
//
//    @Benchmark
//    public void lettuce_get(){
//        String key = "jedis-test";
//        String s = lettuceService.get(key);
//    }
//
//    @Benchmark
//    public void lettuce_set(){
//        String key = "lettuce-test";
//        lettuceService.set(key,"12");
//    }
//
    @Benchmark
    public void redis_get(){
        String key = "redis_get";
        String s = lettuce.get(key);
    }

    @Benchmark
    public void redis_set(){
        String key = "redis_set";
        lettuce.set(key,"redis_get");
    }

    @Benchmark
    public void Lettucepool_get(){
        String key = "redis_get";
        String s = lettucePool.get(key);
    }

    @Benchmark
    public void Lettucepool_set(){
        String key = "redis_set";
        lettucePool.set(key,"redis_get");
    }
    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(MyBenchmark.class.getSimpleName())
                .resultFormat(ResultFormatType.TEXT)
                .result("H:\\Project\\ProjectDemo\\project_demo\\JMH-benchmark\\src\\main\\resources\\result.log")
                .build();

        new Runner(options).run();
    }


}
